﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfApplication1
{
    /// <summary>
    /// Recycle.xaml 的交互逻辑
    /// </summary>
    public partial class Recycle : Window
    {
        private bool listBoxAnimationCompleted = true;
        private List<RecycleResInfoModel> listViewSource = new List<RecycleResInfoModel>();
        private RecycleKeywordsDataManager dataManager = new RecycleKeywordsDataManager();

        public Recycle()
        {
            InitializeComponent();

            //获取当前显示器屏幕
            this.MaxWidth = SystemParameters.WorkArea.Width;
            this.MaxHeight = SystemParameters.WorkArea.Height;

            dataManager.getFirstPageData(refreshListViewSource,getRecycleKeywordsError);
        }

        #region 弹窗关闭图片响应事件
        //鼠标弹起 关闭窗口
        private void CloseImage_MouseUp(object sender, MouseButtonEventArgs e)
        {
            Close();
        }
        //鼠标移入
        private void CloseImage_MouseEnter(object sender, MouseEventArgs e)
        {
            CloseImage.Opacity = 1;
        }
        //鼠标移出
        private void CloseImage_MouseLeave(object sender, MouseEventArgs e)
        {
            CloseImage.Opacity = 0.5;
        }
        #endregion

        #region 弹窗放大图片响应事件
        //鼠标弹起 放大或缩小窗口
        private void EnlargeImage_MouseUp(object sender, MouseButtonEventArgs e)
        {
            Grid gd = this.Template.FindName("grid", this) as Grid;
            //如果是全屏,则最小化
            if (this.WindowState == WindowState.Maximized)
            {
                gd.Margin = new Thickness(5);
                this.Topmost = false;
                this.WindowState = WindowState.Normal;
            }
            //如果是窗口,则全屏
            else if (this.WindowState == WindowState.Normal)
            {
                gd.Margin = new Thickness(0);
                this.WindowState = WindowState.Maximized;
            }
        }
        //鼠标移入
        private void EnlargeImage_MouseEnter(object sender, MouseEventArgs e)
        {
            EnlargeImage.Opacity = 1;
        }
        //鼠标移出
        private void EnlargeImage_MouseLeave(object sender, MouseEventArgs e)
        {
            EnlargeImage.Opacity = 0.5;
        }
        #endregion

        //鼠标按住导航栏 拖动窗口
        private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                this.DragMove();
            }
        }

        #region 来源选择
        //选择来源框点击
        private void ChooseSourceGrid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (!listBoxAnimationCompleted)
            {
                return;
            }
            else
            {
                listBoxAnimationCompleted = false;
            }

            if (listBox.Visibility == Visibility.Hidden)
            {
                listBoxShow();
            }
            else
            {
                listBoxHidden();
            }
            
        }
        //来源下拉框显示动画完成
        private void listBoxShowAnimationOnCompleted(object sender, EventArgs eventArgs)
        {
            listBoxAnimationCompleted = true;
        }
        //来源下拉框隐藏动画完成
        private void listBoxHiddenAnimationOnCompleted(object sender, EventArgs eventArgs)
        {
            listBoxAnimationCompleted = true;
            listBox.Visibility = Visibility.Hidden;
        }
        //来源下拉框某条记录点击
        private void Border_MouseDown(object sender, MouseButtonEventArgs e)
        {
            selectedSourceLabel.Content = ((ListBoxItem)((Border)sender).TemplatedParent).Content;
            listBox.SelectedItem = (ListBoxItem)((Border)sender).TemplatedParent;
            listBox.Visibility = Visibility.Hidden;
            triangleImageAnimation(180, 0);

            switch (listBox.SelectedIndex)
            {
                case 0: dataManager.requestModel.sourceFlag = 2;
                    break;
                case 1:
                    dataManager.requestModel.sourceFlag = 0;
                    break;
                case 2:
                    dataManager.requestModel.sourceFlag = 1;
                    break;
                default:
                    break;
            }

            dataManager.getFirstPageData(refreshListViewSource, getRecycleKeywordsError);
        }
        //来源下拉框隐藏
        private void listBoxHidden()
        {
            ThicknessAnimation marginAnimation = new ThicknessAnimation();
            marginAnimation.To = new Thickness(74, 95, 0, 0);
            marginAnimation.Completed += listBoxHiddenAnimationOnCompleted;

            marginAnimation.Duration = TimeSpan.FromSeconds(0.1);
            listBox.BeginAnimation(MarginProperty, marginAnimation);

            triangleImageAnimation(180, 0);
        }
        //来源下拉框显示
        private void listBoxShow()
        {
            ThicknessAnimation marginAnimation = new ThicknessAnimation();
            listBox.Visibility = Visibility.Visible;
            marginAnimation.To = new Thickness(74, 95, 0, -112);
            marginAnimation.Completed += listBoxShowAnimationOnCompleted;

            marginAnimation.Duration = TimeSpan.FromSeconds(0.1);
            listBox.BeginAnimation(MarginProperty, marginAnimation);

            triangleImageAnimation(0, 180);
        }
        //三角箭头动画
        private void triangleImageAnimation(Double fromValue,Double toValue)
        {
            RotateTransform rtf = new RotateTransform();
            triangleImage.RenderTransform = rtf;
            DoubleAnimation dbAscending = new DoubleAnimation(fromValue, toValue, new Duration

            (TimeSpan.FromSeconds(0.2)));
            dbAscending.RepeatBehavior = new RepeatBehavior(1);
            rtf.BeginAnimation(RotateTransform.AngleProperty, dbAscending);
        }

        #endregion

        //搜索框内容改变
        private void searchBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (searchBox.Text.Length == 0)
            {
                placeholderTextBox.Visibility = Visibility.Visible;
            }
            else
            {
                placeholderTextBox.Visibility = Visibility.Hidden;
            }

            dataManager.requestModel.searchString = (searchBox.Text == null ? "" : searchBox.Text); 
        }

        //搜索框按下回车键
        private void searchBox_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                dataManager.getFirstPageData(refreshListViewSource, getRecycleKeywordsError);
            }
        }

        //搜索关键词
        private void searchImage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            dataManager.getFirstPageData(refreshListViewSource,getRecycleKeywordsError);
        }

        //更新关键词总数
        private void updateTotalCountKeywords(int totalCount)
        {
            Run run = new Run();
            foreach (Run r in totalCountTextBlock.Inlines)
            {
                if (r.Foreground.ToString() == "#FFCC0033")
                {
                    run = r;
                }
            }

            run.Text = totalCount.ToString();
        }

        #region 关键词列表
        //每行复选框取消选中
        private void listViewCheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            allCheckBox.IsChecked = false;

            bool isAllUnSelected = false;

            foreach (var item in listView.Items)
            {
                ListViewItem listViewItem = this.listView.ItemContainerGenerator.ContainerFromItem(item) as ListViewItem;
                CheckBox checkBox = FindVisualChild<CheckBox>(listViewItem);

                if ((bool)checkBox.IsChecked)
                {
                    isAllUnSelected = true;

                    break;
                }
            }

            if (!isAllUnSelected)
            {
                allListItemUnChecked();
            }
        }
        //每行复选框选中
        private void listViewCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            listItemChecked();

            bool isAllSelected = true;

            foreach (var item in listView.Items)
            {
                ListViewItem listViewItem = this.listView.ItemContainerGenerator.ContainerFromItem(item) as ListViewItem;
                CheckBox checkBox = FindVisualChild<CheckBox>(listViewItem);

                if (!(bool)checkBox.IsChecked)
                {
                    isAllSelected = false;

                    break;
                }
            }

            if (isAllSelected)
            {
                allCheckBox.IsChecked = true ;
            }
        }
        //复选框选中后的处理
        private void listItemChecked()
        {
            allRemoveBlock.IsEnabled = true;
            allRemoveBlock.Foreground = new SolidColorBrush(Color.FromRgb(00, 152, 215));
            allRemoveImage.Source = new BitmapImage(new Uri("RecylceImageIcon/removeItemIcon_enable.png", UriKind.Relative));
        }
        //所有复选框未选中后的处理
        private void allListItemUnChecked()
        {
            allRemoveBlock.IsEnabled = false;
            allRemoveBlock.Foreground = new SolidColorBrush(Color.FromRgb(153, 153, 153));
            allRemoveImage.Source = new BitmapImage(new Uri("RecylceImageIcon/removeItemIcon_disabled.png", UriKind.Relative));
        }
        //查找一行上的某个控件
        private ChildType FindVisualChild<ChildType>(DependencyObject obj) where ChildType : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is ChildType)
                {
                    return child as ChildType;
                }
                else
                {
                    ChildType childOfChildren = FindVisualChild<ChildType>(child);
                    if (childOfChildren != null)
                    {
                        return childOfChildren;
                    }
                }
            }
            return null;
        }
        //全选复选框点击
        private void allCheckBox_Click(object sender, RoutedEventArgs e)
        {
            foreach (var item in listView.Items)
            {
                ListViewItem listViewItem = this.listView.ItemContainerGenerator.ContainerFromItem(item) as ListViewItem;
                CheckBox checkBox = FindVisualChild<CheckBox>(listViewItem);
                checkBox.IsChecked = (bool)allCheckBox.IsChecked;
            }

            if ((bool)allCheckBox.IsChecked)
            {
                listItemChecked();
            }
            else
            {
                allListItemUnChecked();
            }
        }
        //批量移出按钮点击
        private void allRemoveBlock_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            List<int> removeList = new List<int>();
            foreach (var item in listView.Items)
            {
                ListViewItem listViewItem = this.listView.ItemContainerGenerator.ContainerFromItem(item) as ListViewItem;
                CheckBox checkBox = FindVisualChild<CheckBox>(listViewItem);

                if ((bool)checkBox.IsChecked)
                {
                    removeList.Add(Convert.ToInt32(checkBox.Tag.ToString()));
                }
            }

            deleteListViewItems(removeList);
            allListItemUnChecked();
            allCheckBox.IsChecked = false;
        }
        //某行移出按钮点击
        private void itemRemoveTextBlock_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            int xh = Convert.ToInt32(((TextBlock)sender).Tag.ToString());
            deleteListViewItems(new List<int>(){ xh });
        }

        //批量删除回收库中的关键词
        private void deleteListViewItems(List<int> list)
        {
            dataManager.removeRecycleKeyword(list,
                    () =>
                    {
                        MessageBox.Show("关键词已成功移出回收库");

                        if (listViewSource.Count == list.Count)
                        {
                            if (dataManager.requestModel.pageIndex == 1)
                            {
                                dataManager.getFirstPageData(refreshListViewSource, getRecycleKeywordsError);
                            }
                            else
                            {
                                dataManager.getPreviousPageData(refreshListViewSource, getRecycleKeywordsError);
                            }
                        }
                        else
                        {
                            dataManager.getPageDataWithPageIndex(dataManager.requestModel.pageIndex, refreshListViewSource, getRecycleKeywordsError);
                        }
                    },
                    exception =>
                    {
                        MessageBox.Show(exception.ToString());
                    });
        }

        //刷新数据源
        private void refreshListViewSource(List<RecycleResInfoModel> list)
        {
            foreach (RecycleResInfoModel listModel in list)
            {
                foreach (RecycleResInfoModel listViewSourceModel in listView.Items)
                {
                    if (listViewSourceModel.XH == listModel.XH)
                    {
                        listModel.IsChecked = listViewSourceModel.IsChecked;
                        break;
                    }
                }
            }

            Dispatcher.BeginInvoke(new Action(delegate
            {
                listView.ItemsSource = listViewSource = list;
                updateUI();
            }));
        }

        private void getRecycleKeywordsError(WebException exception)
        {
            MessageBox.Show(exception.ToString());
            listViewSource.Clear();
            listView.Items.Refresh();
        }

        private void updateUI()
        {
            updateTotalCountKeywords(dataManager.totalCount);

            totalPageTextBlock.Text = "共" + dataManager.totalPage.ToString() + "页";

            Run run = new Run();
            foreach (Run r in currentPageTextBlock.Inlines)
            {
                if (r.Foreground.ToString() == "#FFCC0033")
                {
                    run = r;
                }
            }

            run.Text = dataManager.requestModel.pageIndex.ToString();

            string currentPageTextBlockText = "";
            foreach (Run r in currentPageTextBlock.Inlines)
            {
                currentPageTextBlockText = currentPageTextBlockText + r.Text;
            }

            currentPageTextBlock.ToolTip = currentPageTextBlockText;
        }

        #endregion

        #region 分页控件操作
        //页码输入框限制只能输入数字
        private void searchPageTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            //判断shifu键是否按下
            bool shiftKey = (Keyboard.Modifiers & ModifierKeys.Shift) != 0;

            if (shiftKey == true)//当按下shift
            {
                e.Handled = true;//不可输入
            }
            else//未按shift
            {
                if (!((e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Delete || e.Key == Key.Back || e.Key == Key.Tab || e.Key == Key.Enter))
                {
                    e.Handled = true;//不可输入
                }
            }
        }
        //跳转到某页
        private void GO_Buton_Click(object sender, RoutedEventArgs e)
        {
            if (searchPageTextBox.Text.Length == 0)
            {
                MessageBox.Show("请输入要跳转的页码");
            }
            else if (Convert.ToInt32(searchPageTextBox.Text) == 0)
            {
                MessageBox.Show("跳转的页码必须大于0");
            }
            else if (Convert.ToInt32(searchPageTextBox.Text) > dataManager.totalPage)
            {
                MessageBox.Show("跳转的页码不能大于总页数");
            }
            else
            {
                dataManager.getPageDataWithPageIndex(Convert.ToInt32(searchPageTextBox.Text), refreshListViewSource, getRecycleKeywordsError);
            }
        }
        //最后一页
        private void lastPageTextBlock_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            dataManager.getLastPageData(refreshListViewSource, getRecycleKeywordsError);
        }
        //第一页
        private void firstPageTextBlock_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            dataManager.getFirstPageData(refreshListViewSource, getRecycleKeywordsError);
        }
        //下一页
        private void nextPageTextBlock_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (dataManager.requestModel.pageIndex == dataManager.totalPage)
            {
                return;
            }

            dataManager.getNextPageData(refreshListViewSource, getRecycleKeywordsError);
        }
        //上一页
        private void previousPageTextBlock_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (dataManager.requestModel.pageIndex == 1)
            {
                return;
            }

            dataManager.getPreviousPageData(refreshListViewSource, getRecycleKeywordsError);
        }

        #endregion
    }
}
